package activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ilioili.proabslist.ListStateListener;
import com.ilioili.proabslist.ProAbsListView;
import com.laoxinwen.app.R;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

import bean.HotKeyWord;
import bean.TabTopicItem;
import bean.wraper.HotKeyWordWraper;
import bean.wraper.TabTopicListWrapper;
import cn.evun.proabslistview.FreshView;
import cn.evun.proabslistview.LoadView;
import common.BaseActivity;
import common.CommonHolder;
import common.FastAdapter;
import common.HttpCallBack;
import common.Requester;
import view.SearchKeyView;

@SuppressLint("SimpleDateFormat")

/**
 * Created by ilioili on 2015/1/13.
 */ public class SearchActivity extends BaseActivity implements ListStateListener {
    Calendar calendar = Calendar.getInstance();
    private ArrayList<TabTopicItem> dataList = new ArrayList<TabTopicItem>();
    private SimpleDateFormat dayFormater = new SimpleDateFormat("MM-dd");
    @id(R.id.et_search)
    private EditText etSearch;
    private HashSet<Object> expandedSet = new HashSet<Object>();
    private List<HotKeyWord> hotKeyWordList = new ArrayList<>();
    private FastAdapter adapter = new FastAdapter() {

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CommonHolder.TopicHolder holder = null;
            TabTopicItem tabTopicItem = dataList.get(position);
            if (null == convertView) {
                convertView = LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_topic_origin, parent, false);
                holder = new CommonHolder.TopicHolder(convertView, SearchActivity.this);
            } else {
                holder = (CommonHolder.TopicHolder) convertView.getTag();
            }
            holder.setData(tabTopicItem);
            return convertView;
        }

    };
    private boolean isRequestingData;
    private String keyword;
    @id(R.id.listView)
    private ListView listView;
    private int pageIndex = 0;
    @id(R.id.proAbsListView)
    private ProAbsListView proAbsListView;
    @id(R.id.search_view)
    private SearchKeyView searchKeyView;


    @Override
    public void onScrollWhileFreshViewVisible(int percentage) {

    }

    @Override
    public void onScrollWhileLoadViewVisible(int percentage) {

    }

    @Override
    public void onStartFreshing() {
        hideInputKeyboard();
        if (isRequestingData) {
            Toast.makeText(SearchActivity.this, "数据正在加载中", Toast.LENGTH_SHORT).show();
        } else {
            pageIndex = 0;
            requestData();
        }

    }

    @Override
    public void onStartLoading() {
        pageIndex++;
        requestData();
    }

    private void requestData() {
        isRequestingData = true;
        Requester.searchNewsGroup(keyword, pageIndex, new HttpCallBack<TabTopicListWrapper>() {
            @Override
            public void onSucceed(TabTopicListWrapper t) {
                TabTopicListWrapper newsGroupWraper = t;
                if (null != newsGroupWraper.getData()) {
                    if (pageIndex == 0) {
                        dataList.clear();
                    }
                    dataList.addAll(newsGroupWraper.getData());
                    if (!dataList.isEmpty()) {
                        expandedSet.add(dataList.get(0));
                    }
                }
                if (dataList.isEmpty()) {
                    showToast("亲， 没有搜索到相关新闻呢，欢迎给我们提供事件思路！");
                    searchKeyView.setVisibility(View.VISIBLE);
                    proAbsListView.setVisibility(View.GONE);
                } else {
                    searchKeyView.setVisibility(View.GONE);
                    proAbsListView.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                }
                cancelFreshing();
            }

            @Override
            protected void onNetError() {
                super.onNetError();
                cancelFreshing();
            }

            @Override
            protected void onServerError(TabTopicListWrapper data) {
                super.onServerError(data);
                searchKeyView.setVisibility(View.VISIBLE);
                proAbsListView.setVisibility(View.GONE);
                cancelFreshing();
            }

            private void cancelFreshing() {
                proAbsListView.cancelFreshing();
                proAbsListView.cancelLoading();
                isRequestingData = false;
            }

        });

    }

    @Override
    protected void onRightSlide() {
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_search:
                ivokeSearch();
                break;
            case R.id.bt_clear:
                searchKeyView.setVisibility(View.VISIBLE);
                proAbsListView.setVisibility(View.GONE);
                etSearch.setText(null);
                dataList.clear();
                adapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        loadView();
        proAbsListView.setListStateListener(this);
        setListView();
        setFreshView();
        setLoadView();
        searchKeyView.setOnItemClickListener(new SearchKeyView.OnItemClickListener() {
            @Override
            public void onItemClick(View clickedChildView, int position) {
                etSearch.setText(hotKeyWordList.get(position).getKw());
                etSearch.setSelection(etSearch.getText().length());
                ivokeSearch();
            }
        });
        searchKeyView.setItemResourceId(R.layout.search_key, R.id.tv_key);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    ivokeSearch();
                    return true;
                }
                return false;
            }
        });
        Requester.getSearchHotKeys(new HttpCallBack<HotKeyWordWraper>() {
            @Override
            public void onSucceed(HotKeyWordWraper data) {
                //                hotKeyWordList.add("谢霆锋");
                //                hotKeyWordList.add("劳动人口");
                //                hotKeyWordList.add("反腐");
                //                hotKeyWordList.add("留守妻子");
                //                hotKeyWordList.add("公路体质 改革 收费");
                //                hotKeyWordList.add("街头 反腐漫画");
                //                hotKeyWordList.add("亚航 失事");
                List<HotKeyWord> list = data.getData();
                hotKeyWordList.addAll(data.getData());
                for (HotKeyWord key : hotKeyWordList) {
                    searchKeyView.addItem(key.getKw(), key.getKw());
                }
            }
        });
    }

    private void setListView() {
        listView = (ListView) proAbsListView.getAbsListView();
        listView.setAdapter(adapter);
    }

    private void setFreshView() {
        LoadView loadView = new LoadView(SearchActivity.this);
        proAbsListView.setLoadView(loadView);
    }

    private void setLoadView() {
        FreshView freshView = new FreshView(SearchActivity.this);
        proAbsListView.setFreshView(freshView);
    }

    private void ivokeSearch() {
        keyword = etSearch.getText().toString().trim();
        pageIndex = 1;
        proAbsListView.setVisibility(View.VISIBLE);
        proAbsListView.startFresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("搜索页");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("搜索页");
    }
}
